package com.arvin.faceDetect.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.arvin.faceDetect.databinding.ItemLogFileBinding
import com.arvin.faceDetect.model.LogFile

class LogFileAdapter(
    private val onItemClick: (LogFile) -> Unit,
    private val onItemLongClick: (LogFile) -> Boolean
) : ListAdapter<LogFile, LogFileAdapter.ViewHolder>(LogFileDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemLogFileBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val logFile = getItem(position)
        holder.bind(logFile)
    }

    inner class ViewHolder(
        private val binding: ItemLogFileBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        init {
            itemView.setOnClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    onItemClick(getItem(position))
                }
            }

            itemView.setOnLongClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    onItemLongClick(getItem(position))
                } else {
                    false
                }
            }
        }

        fun bind(logFile: LogFile) {
            binding.tvFileName.text = logFile.name
            binding.tvFileInfo.text =
                "${logFile.getFormattedSize()} · ${logFile.getFormattedTime()}"
        }
    }

    private class LogFileDiffCallback : DiffUtil.ItemCallback<LogFile>() {
        override fun areItemsTheSame(oldItem: LogFile, newItem: LogFile): Boolean {
            return oldItem.file.absolutePath == newItem.file.absolutePath
        }

        override fun areContentsTheSame(oldItem: LogFile, newItem: LogFile): Boolean {
            return oldItem == newItem
        }
    }
} 